﻿#include <sys/socket.h>  // 用于 socket、bind、listen 等函数
#include <arpa/inet.h>   // 包含 inet_addr 等函数
#include <unistd.h>      // 用于 close 等函数
#include <cstring>       // 用于 bzero 等函数
#include <cstdio>        // 用于 printf
#include <iostream>

int main()
{
	
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	//errif(sockfd == -1, "socket create error");
	struct sockaddr_in serv_addr;
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	serv_addr.sin_port = htons(8888);
	bind(sockfd, (sockaddr*)&serv_addr, sizeof(serv_addr));
	listen(sockfd, SOMAXCONN);
	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_len = sizeof(clnt_addr);
	bzero(&clnt_addr, sizeof(clnt_addr));
	
	int clnt_sockfd = accept(sockfd, (sockaddr*)&clnt_addr, &clnt_addr_len);
	
	printf("new client fd %d! IP: %s Port: %d\n", clnt_sockfd, inet_ntoa(clnt_addr.sin_addr), ntohs(clnt_addr.sin_port));

	while (true) {
		char buf[1024];
		bzero(&buf, sizeof(buf));
		ssize_t read_bytes = read(clnt_sockfd, buf, sizeof(buf));
		if (read_bytes > 0) {
			printf("message from client fd %d: %s\n", clnt_sockfd, buf);
			write(clnt_sockfd, buf, sizeof(buf));
		}
		else if (read_bytes == 0) {
			printf("client fd %d disconnected\n", clnt_sockfd);
			close(clnt_sockfd);
			break;
		}
		else if (read_bytes == -1) {
			close(clnt_sockfd);
			//errif(true, "socket read error");
		}
	}


	close(clnt_sockfd);
	close(sockfd);
    
	


	return 0;
}